<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { onMounted, ref } from 'vue'
  import DateRange from '@/components/business/date-range/DateRange.vue'
  import {
    useGetWarehouseOutList,
    useWarehouseOutWriteBack,
  } from '@/services/pages/storage/useWarehouseOut'
  // import fixedData from '@/config/fixed-data/warehouse/out-store'
  import { useRouter } from 'vue-router'
  import routeComponentName from '@/config/route-component-name'
  import { ElMessageBox, TableInstance } from 'element-plus'
  import { HMessage, HMessageBox } from '@/components/common/message'

  const { list, listTotal, getListParam, getListLoading, getList } = useGetWarehouseOutList()
  const { writeBackLoading, writeBack } = useWarehouseOutWriteBack()

  defineOptions({
    name: routeComponentName.storage.materialWarehouseOutApplyList,
  })

  // 选择的出库列表
  const selectionList = ref<Array<WarehouseOut>>([])

  // 全局路由对象
  const router = useRouter()

  // 分页组件实例
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 日期类型
  const dateTypeList = [
    { title: '今天', value: 2 },
    { title: '本周', value: 3 },
    { title: '本月', value: 4 },
    { title: '自定义时间', value: 1 },
  ]

  // 单据来源
  const sourceList = [
    { title: '系统单', value: 1 },
    { title: '工单', value: 2 },
    { title: 'ERP单据', value: 3 },
    // { title: '仓库移动端单据', value: 4 },
    // { title: '第三方系统单据', value: 5 },
    // { title: '用友', value: 6 },
    { title: '网点移动端单据', value: 7 },
  ]

  // 出库单状态
  const statusList = [
    { title: '待审核', value: 1 },
    { title: '待出库', value: 2 },
    { title: '驳回', value: 3 },
    { title: '已出库', value: 4 },
    { title: '已作废', value: 5 },
  ]

  // 出库仓类型
  const storeTypeList = [
    { title: '内部仓库', value: 0 },
    { title: '网点-外部仓库', value: 1 },
    { title: '工程师-外部仓库', value: 2 },
  ]

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  /**
   * 获取列表
   */
  const _getList = () => {
    if (paginationInstance.value) {
      getListParam.value.type = 2
      getListParam.value.limit = paginationInstance.value.size
      getListParam.value.page = paginationInstance.value.current
      getList()
    }
  }

  /**
   * 日期类型更新事件
   */
  const onDateTypeChange = () => {
    if (getListParam.value.dateType !== 1) {
      _getList()
    }
  }

  /**
   * 获取仓库类型渲染文本
   * @param {0|1|2} type - 仓库类型
   */
  const getStoreTypeRenderText = (type: 0 | 1 | 2) => {
    const storeType = storeTypeList.find((item) => item.value === type)
    if (storeType) {
      return storeType.title
    }
  }

  /**
   * 获取单据来源渲染文本
   * @param {1|2|3|4|5|6|7} type - 来源类型
   */
  const getSrouceRenderText = (type: 1 | 2 | 3 | 4 | 5 | 6 | 7) => {
    const source = sourceList.find((item) => item.value === type)
    if (source) {
      return source.title
    }
  }

  /**
   * 收货地址类型渲染文本
   * @param {1|2|3|4|5} addressType - 收货地址类型
   */
  const getReceiptAddressTypeRenderText = (addressType: 1 | 2 | 3 | 4 | 5) => {
    if (addressType === 1) {
      return '公司'
    }

    if (addressType === 2) {
      return '网点仓库'
    }

    if (addressType === 3) {
      return '工程师仓库'
    }

    if (addressType === 4) {
      return '他收货人（此收获类型仅用于工单物料出库）'
    }

    if (addressType === 5) {
      return '销售网点'
    }

    return ''
  }

  /**
   * 详情点击事件
   * @param {WarehouseOut} warehouseOut - 出库对象
   */
  const handleDetailClick = (warehouseOut: WarehouseOut) => {
    if (warehouseOut.status == 1) {
      router.push(`/storage/newout/${warehouseOut.id}/${2}`)
    } else {
      router.push('/storage/outb/detail/' + warehouseOut.id)
    }
  }

  /**
   * 单个反写/批量反写
   * @param {Array<WarehouseOut>} warehouseOutList - 需要反写的出库单集合
   */
  const handleWriteBack = (warehouseOutList: Array<WarehouseOut>) => {
    for (let i = 0; i < warehouseOutList.length; i++) {
      const warehouseOut = warehouseOutList[i]

      if (warehouseOut.reverseWritingStatus === 2) {
        HMessageBox.warning('不能选择反写成功的单据')
        return
      }
    }

    if (warehouseOutList.length === 1 && tableInstance.value) {
      tableInstance.value.clearSelection()
      tableInstance.value.toggleRowSelection(warehouseOutList[0])
    }
    ElMessageBox({
      title: '提示',
      type: 'warning',
      message: warehouseOutList.length === 1 ? '确定要反写当前出库单' : '确定要反写选择的出库单',
      autofocus: false,
      showCancelButton: true,
      async beforeClose(action, instance, done) {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.cancelButtonLoading = true
          const res = await writeBack(warehouseOutList.map((itme) => itme.id))
          instance.confirmButtonLoading = false
          instance.cancelButtonLoading = false
          if (res.code === 20000) {
            HMessage.success('反写成功')
            _getList()
            done()
            return
          }
          HMessageBox.error(res.message)
          return
        }
        done()
      },
    })
  }

  /**
   * 表格选择事件
   * @param {Array<WarehouseOut>} list - 选择的列表
   */
  const handleTableSelection = (list: Array<WarehouseOut>) => {
    selectionList.value = list
  }

  /**
   * 新增出库点击事件
   */
  // const handleCreateWarehouseOut = () => {
  //   router.push({
  //     path: '/storage/newout',
  //     query: { documentSourceId: fixedData.order_material_warehouse_out_id },
  //   })
  // }

  /**
   * 工单单号点击事件
   * @param {string} orderId - 工单id
   */
  const handleOrderNoClick = (orderId: string) => {
    router.push({ path: `/order/odetail/${orderId}` })
  }

  /**
   * 重置点击事件
   */
  const onResetClick = () => {
    getListParam.value = {
      dateType: '',
      endTime: '',
      limit: 50,
      page: 1,
      search: '',
      source: '',
      startTime: '',
      status: '',
      type: '',
    }
    _getList()
  }

  onMounted(() => {
    _getList()
  })
</script>

<template>
  <div class="material-apply-list">
    <div v-loading="getListLoading || writeBackLoading" class="container">
      <div class="header">
        <div class="btn-group">
          <!-- <h-plain-button @click="handleCreateWarehouseOut">新增出库</h-plain-button> -->
          <h-plain-button
            :disabled="selectionList.length <= 0"
            @click="handleWriteBack(selectionList)"
          >
            批量反写
          </h-plain-button>
        </div>
        <div class="search">
          <el-select
            v-model="getListParam.dateType"
            class="date-type"
            placeholder="请选择日期类型"
            clearable
            @clear="_getList"
            @change="onDateTypeChange"
          >
            <el-option
              v-for="(dateType, dateTypeIndex) in dateTypeList"
              :key="dateTypeIndex"
              :value="dateType.value"
              :label="dateType.title"
            />
          </el-select>

          <DateRange
            v-if="getListParam.dateType === 1"
            ref="dateRangeRef"
            :start-date-width="140"
            :end-date-width="140"
          />

          <!-- 单据来源 -->
          <el-select
            v-model="getListParam.source"
            class="source"
            clearable
            placeholder="请选择单据来源"
            @clear="_getList"
            @change="_getList"
          >
            <el-option
              v-for="item in sourceList"
              :key="item.value"
              :value="item.value"
              :label="item.title"
            />
          </el-select>

          <!-- 出库单状态 -->
          <el-select
            v-model="getListParam.status"
            placeholder="请选择出库单状态"
            clearable
            class="status"
            @change="_getList"
            @clear="_getList"
          >
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :value="item.value"
              :label="item.title"
            />
          </el-select>

          <!-- 出库单号/收货人/手机号/制单人 -->
          <el-input
            v-model.trim="getListParam.search"
            clearable
            placeholder="请输入出库单号/收货人/手机号/制单人"
            class="input"
            @clear="_getList"
            @change="_getList"
          />

          <h-button type="primary" @click="_getList">
            <el-icon>
              <Search></Search>
            </el-icon>
            搜索
          </h-button>

          <h-button @click="onResetClick">
            <el-icon>
              <RefreshRight />
            </el-icon>
            重置
          </h-button>
        </div>
      </div>
      <div class="main">
        <div class="table">
          <el-table
            ref="tableInstance"
            :border="true"
            :data="list"
            height="100%"
            @selection-change="handleTableSelection"
          >
            <!-- 多选 -->
            <el-table-column fixed="left" width="50" :align="'center'" type="selection" />

            <!-- 序号 -->
            <el-table-column label="序号" fixed="left" width="50" :align="'center'" type="index" />

            <!-- 出库单号 -->
            <el-table-column
              show-overflow-tooltip
              prop="outboundNo"
              fixed
              label="出库单号"
              width="130"
            >
              <template #default="{ row }">
                <h-link @click="handleDetailClick(row)">{{ row.outboundNo }}</h-link>
              </template>
            </el-table-column>

            <!-- 工单单号 -->
            <el-table-column show-overflow-tooltip prop="workNo" fixed label="工单单号" width="130">
              <template #default="{ row }">
                <h-link @click="handleOrderNoClick(row.workId)">{{ row.workNo }}</h-link>
              </template>
            </el-table-column>

            <el-table-column
              show-overflow-tooltip
              prop="kdYunxkThirdCode"
              fixed
              label="返回单号"
              width="150"
            />

            <!-- 仓库名称 -->
            <el-table-column show-overflow-tooltip prop="store" label="仓库名称" min-width="120" />

            <!-- 仓库类型 -->
            <el-table-column show-overflow-tooltip label="仓库类型" width="90">
              <template #default="{ row }">
                {{ getStoreTypeRenderText(row.storeType) }}
              </template>
            </el-table-column>

            <!-- 反写状态 -->
            <el-table-column show-overflow-tooltip label="反写状态" width="120">
              <template #default="{ row }">
                <h-status v-if="row.reverseWritingStatus === 1" type="error">反写失败</h-status>
                <h-status v-if="row.reverseWritingStatus === 2">反写成功</h-status>
              </template>
            </el-table-column>

            <!-- 反写失败原因 -->
            <el-table-column show-overflow-tooltip label="反写失败原因" width="120">
              <template #default="{ row }">
                {{ row.reverseWritingStatus === 1 ? row.reverseWritingFailReason : '' }}
              </template>
            </el-table-column>

            <!-- 收获名称 -->
            <el-table-column show-overflow-tooltip label="收货名称" min-width="150">
              <template #default="{ row }">
                {{ row.receiptName }}&nbsp;{{ row.receiptPhone }}
              </template>
            </el-table-column>

            <!-- 单据来源 -->
            <el-table-column show-overflow-tooltip label="单据来源" width="120">
              <template #default="{ row }">{{ getSrouceRenderText(row.source) }}</template>
            </el-table-column>

            <!-- 收货地址类型 -->
            <el-table-column show-overflow-tooltip label="收货地址类型" width="100">
              <template #default="{ row }">{{
                getReceiptAddressTypeRenderText(row.receiptAddrType)
              }}</template>
            </el-table-column>

            <!-- 制单人 -->
            <el-table-column show-overflow-tooltip prop="createEmp" label="制单人" width="80" />

            <!-- 制单时间 -->
            <el-table-column show-overflow-tooltip prop="createTime" label="制单时间" width="128" />

            <!-- 最后更新时间 -->
            <el-table-column
              show-overflow-tooltip
              prop="updateTime"
              label="最后更新时间"
              width="128"
            />

            <!-- 出库单状态 -->
            <el-table-column
              prop="status"
              label="出库单状态"
              width="88"
              :align="'center'"
              fixed="right"
            >
              <template #default="{ row }">
                <div class="flex_justify_center">
                  <h-status v-if="row.status === 1" type="warning">待审核</h-status>
                  <h-status v-if="row.status === 2" type="warning">待出库</h-status>
                  <h-status v-if="row.status === 3" type="info">已驳回</h-status>
                  <h-status v-if="row.status === 4" type="success">已出库</h-status>
                  <h-status v-if="row.status === 5" type="error">已作废</h-status>
                </div>
              </template>
            </el-table-column>

            <!-- 操作 -->
            <el-table-column label="操作" width="100" fixed="right" :align="'center'">
              <template #default="{ row }">
                <h-space>
                  <h-link @click="handleDetailClick(row)">详情</h-link>
                  <h-link v-if="row.reverseWritingStatus === 2" :disabled="true"> 反写 </h-link>
                  <h-link v-else @click="handleWriteBack([row])"> 反写 </h-link>
                </h-space>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <pagination
            ref="paginationInstance"
            :list_total="listTotal"
            @size-change="_getList"
            @current-change="_getList"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
  .material-apply-list {
    height: calc(100vh - 92px);
    width: 100%;
    padding: 12px;
    box-sizing: border-box;

    .container {
      padding: 12px;
      box-sizing: border-box;
      background-color: #fff;
      height: 100%;
      display: flex;
      flex-direction: column;
      row-gap: 12px;

      .header {
        display: flex;
        justify-content: space-between;

        .btn-group {
          display: flex;
          column-gap: 5px;
        }

        .search {
          display: flex;
          column-gap: 5px;

          .date-type {
            width: 140px;
          }

          .source,
          .status {
            width: 140px;
          }

          .input {
            width: 240px;
          }
        }
      }

      .main {
        flex: 1;
        height: 0;
        display: flex;
        row-gap: 12px;
        flex-direction: column;

        .table {
          max-height: calc(100% - 40px);
        }

        .pagination {
          display: flex;
          justify-content: flex-end;
        }
      }
    }
  }
</style>
